#!/usr/bin/env python
# coding=utf-8
import MySQLdb
import re,string,urllib,urllib2,time

database_db='flightdb'
username_db='flight_dbuser'
server_db='192.168.1.71'
password_db='fligdb56'
conn=MySQLdb.Connection(server_db,username_db,password_db,database_db,use_unicode=True,charset='utf8')


url='http://airchina.travelsky.com/cab2c/FlightSearch_n.do?adultTravelers=1&airkind=oneway&cabinClass=special&childTravelers=0&dstCity=%s&isContractSale=N&lan=CN&needCalShop=onlyselect&orgCity=%s&orgID=CAB2C&returnDate=%s&returnTime=&step=1&takeoffDate=%s&takeoffTime=&travelers=1&tripType=oneway'
re_cabin=re.compile(r"changeprice1\([^,]+,[^,]+,'([0-9]+)[^>]+></div>\s*([A-z]+)舱", re.X|re.S)

try:
    curs=conn.cursor()
    try:
        sql="SELECT depport,arrport FROM airline WHERE venders REGEXP 'CA' AND isInternational=0 AND depport='CAN' AND arrport='PEK'"
        #sql="SELECT depport,arrport FROM airline WHERE venders REGEXP 'CA' AND isInternational=0"
        curs.execute(sql)
        list = curs.fetchall()
        for r in list:
            params=(r[1],r[0],'2010-11-25','2010-11-25')
            try:
                print url % params
                print r[0],r[1]        
                html = urllib2.urlopen(url % params).read().decode("gbk").encode("utf-8")
                cabin_pts=re_cabin.findall(html)
                c_dict={}
                for c in cabin_pts:
                    c_dict[c[1]]=c[0]
                for k in c_dict.keys():
                    print k,c_dict[k]
                    curs.callproc('PROC_OYESGO_FLIGHT_AIRPOLICY_UPD',('CA',params[0],params[1],k,c_dict[k]))
                    conn.commit()
            except Exception,e:
                print e 
            time.sleep(180);
    finally:
        curs.close()
finally:
    conn.close()
'''
params=('CAN','SHA','2010-11-20','2010-11-20')
try:        
    html = urllib2.urlopen(url % params).read().decode("gbk").encode("utf-8")
    cabin_pts=re_cabin.findall(html)
    c_dict={}
    for c in cabin_pts:
        c_dict[c[1]]=c[0]
    for k in c_dict.keys():
        print k,c_dict[k]
except Exception,e:
    print e            
''' 
